import React, { Component } from 'react';
import Taro, { Config, getCurrentInstance } from '@tarojs/taro';
import { ScrollView, View, Image, Text } from '@tarojs/components'
import { AtButton, AtMessage, AtFloatLayout } from 'taro-ui'
import CarInfo from '@/components/CarInfo'
import { connect } from 'react-redux'
import Iconfont from '@/components/Iconfont'
import { createCart } from '@/api/goods'
import classnames from 'classnames'
import { getDefaultList, getLaborFee, getCouponList, receiveCoupon, getDiscountTip } from '@/api/maintain'
import { debounce,accAdd ,throttle} from '@/utils'
import cloneDeep from 'lodash/cloneDeep'
import { storeInfo } from '@/api'
import qs from 'qs'

import './index.scss'

type State = {
  isFix: boolean
  navIndex: number
  scrollTop: number
  diyList: Array<any>
  List: Array<any>
  tabs: Array<any>
  form: any
  totalPrice: any
  loading: boolean
  current: number,
  _scrollIntoView: string,
  diffCategoryDialog: any
  couponDialog: any
  giftRuleList: Array<any>
	selectStore:object
}

@connect<any>(({ car, maintain }) => ({ car, maintain }))

export default class MaintainIndex extends Component<any, State> {
  $instance = getCurrentInstance();
  protected bannerH: number
  protected currentTabKey: number = 0
  protected params: any = {}
  protected isCanSubmitFlag: boolean = true
  protected cartImg: string = `${SOURCES_PATH}/img/annual/cart.png`
  protected jekunModelCode: string
  constructor() {
    super(...arguments)
    this.state = {
      isFix: false,
      navIndex: 0,
      scrollTop: 0,
      diyList: [],
      List: [],
      tabs: [],
      form: {
        items: 2
      },
      totalPrice: {
        goodsPrice: '--',
        originGoodsPrice: '--',
        remainAmount: '--'
      },
      diffCategoryDialog: {
        show: false,
        title: '',
        data: new Array(),
        currentCategoryKey: 0,
        receiveIndex: 0
      },
      couponDialog: {
        show: false,
        data: new Array(),
        sendType: 1,
        projectId: 0
      },
      giftRuleList: [],
      loading: true,
      current: 0,
      _scrollIntoView: '',
			selectStore:{}
    }
  }
  static options = {
    addGlobalClass: true
  }

  handleClick(item) {
    // Taro.navigateTo({
    //   url: `/pages/detection/detail/index?reportId=${item.reportId}&title=${item.typeLabel}`
    // })
		console.log('item',item)
		Taro.navigateTo({
      url: `/pages/goods/details/index?id=${item.goodsId}`
    })

  }
  onScroll(e) {

  }
  UNSAFE_componentWillMount() {}

	async componentDidShow(){
		let pages = Taro.getCurrentPages();
		let currentPage = pages[pages.length - 1]; // 获取当前页面
		if (currentPage.__data__.selectStore) { // 获取值
			this.setState({
				selectStore: currentPage.__data__.selectStore
			})
			console.log('进来的selectStore数据',currentPage.__data__.selectStore)
		}
	}
  async componentDidMount() {
    this.params = this.$instance.router.params

		let {storeCode} = this.$instance.router.params
		let code = storeCode || Taro.getStorageSync('STORECODE') || ''
		console.log('code',code)
		if (code) {
      let storeParams: any = {
        storeCode:code
      }
			storeParams = {
				...storeParams,
				userLongitude:'',
				userLatitude:''
			}
      const result = await storeInfo(storeParams)
      const data = result.data['data']
			console.log('data门店的数据',data)
      this.setState({
        selectStore: data,
      })
    }

    if (this.props.car.carInfo.currentCar) {
      this.jekunModelCode = this.props.car.carInfo.currentCar.jekunModelCode
      Promise.all([this.getDefaultList(this.jekunModelCode), this.getDiscountTip()])
    }

  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    let carInfo = nextProps.car.carInfo
    let oldCarInfo = this.props.car.carInfo.currentCar
    if ((carInfo.currentCar && !oldCarInfo) || (oldCarInfo && oldCarInfo.carLicense !== carInfo.currentCar.carLicense)) {
      this.resetDefaultList()
      this.jekunModelCode = nextProps.car.carInfo.currentCar.jekunModelCode
      Promise.all([this.getDefaultList(this.jekunModelCode), this.getDiscountTip()])
      return
    }

    if (nextProps.maintain.projectItem) {
      let { List } = this.state
      let newList = [...List]
      let projectItem = nextProps.maintain.projectItem
      let { tabKey, categoryKey, projectKey } = projectItem
      newList[tabKey].items[categoryKey].isEdit = false
      newList[tabKey].items[categoryKey].projectItems[projectKey].goodsItems = projectItem.goodsItems
      this.setState({
        List: newList
      }, () => {
        this.calcProjectTotalPriceAndLaborFee(tabKey, categoryKey)
      })
    }
  }

  getDefaultList=async(jekunModelCode) =>{
    Taro.showLoading({
      title: '加载中...'
    })
		let {selectStore} = this.state
		let params = {
      jekunModelCode,
      baseServiceId: this.params.serviceId,
      goodsId: this.params.goodsId,
    }
		if(selectStore.storeCode){
			params.storeCode = selectStore.storeCode
		}
    let res = await getDefaultList(params)
    let data = this.forMatData(res.data.data)
    this.setState({
      tabs: this.setTabs(data),
      current: this.currentTabKey,
      List: this.setTotalLaborFeeAndCounts(data),
      loading: false
    }, () => {
      this.calcTotalPrice()
    })
    Taro.hideLoading()
  }

  resetDefaultList=()=> {
    this.setState({
      tabs: [],
      List: [],
      current: 0
    })
  }

  setTabs=(arr)=> {
    arr = arr.map(i => {
      return {
        tabKey: i.tabKey,
        name: i.name
      }
    })
    return arr
  }

  getDiscountTip =async()=> {
    let res = await getDiscountTip()
    this.setState({
      giftRuleList: res.data.data
    })
  }

  forMatData=(data)=> {
    // let eachBuy = 1
    let _this = this
    let newArr = data.map((i, index) => {
      return {
        ...i,
        tabKey: index,
        items: forMatItem(i.items, index, i)
      }
    })
    function forMatItem(arr: Array<any>, tabKey: number, parent: any): Array<any> {
      arr = arr.map((i, index) => {
        let isCheck = Number(_this.params.projectId) ? Number(_this.params.projectId) === Number(i.projectId) ? true : false : false
        if (isCheck) _this.currentTabKey =  Number(tabKey)
        return {
          ...i,
          isCheck: isCheck,
          isEdit: false,
          tabKey,
          categoryKey: index,
          totalPrice: 0,
          totalPlatformPrice: 0,
          totalLaborFee: 0,
          projectItems: formatProjectItems(i.projectItems, tabKey, index)
        }
      })
      return arr
    }
    function formatProjectItems(arr: Array<any>, tabKey: number, categoryKey: number): Array<any> {
      arr = arr.map((i, index) => {
        return {
          ...i,
          tabKey,
          categoryKey,
          projectKey: index,
          goodsItems: forMatGoodsItem(i.goodsItems, tabKey, categoryKey, index)
        }
      })
      return arr
    }

    function forMatGoodsItem(arr: Array<any>, tabKey: number, categoryKey: number, projectKey: number) {
      arr = arr.map((i, index) => {
        return {
          ...i,
          tabKey,
          categoryKey,
          projectKey,
          goodsKey: index
        }
      })
      return arr
    }
    return newArr
  }
  setTotalLaborFeeAndCounts=(arr: Array<any>): Array<any>=> {
    let _this = this
    arr = arr.map(i => {
      return {
        ...i,
        items: forMatItem(i.items)
      }
    })

    function forMatItem(arr: Array<any>): Array<any> {
      arr = arr.map(i => {
        return {
          ...i,
          totalLaborFee: _this.calcItemTotalLaborFee(i.projectItems),
          totalPrice: _this.calcItemTotalPrice(i.projectItems),
          totalPlatformPrice: _this.calcItemTotalPlatformPrice(i.projectItems)
        }
      })
      return arr
    }
    return arr
  }

  calcItemTotalLaborFee=(arr: Array<any>): number=> {
    let total = 0

    arr.map(i => {
      let isAllGoodsEnty = true
      i.goodsItems.map(goods => {
        if (Number(goods.num) !== 0) {
          isAllGoodsEnty = false
        }
      })
      if (isAllGoodsEnty) i.laborFee = 0
      if (Number(i.laborFee) !== 0 && i.goodsItems.length) {
        total = accAdd(total, Number(i.laborFee))
      }
    })
    return total
  }

  calcItemTotalPrice=(arr: Array<any>)=> {
    let total = 0
    let totalPrice = 0

    arr.map(i => {

      i.goodsItems.map(goodsItem => {
        if (Number(i.laborFee) !== 0 && goodsItem.num && i.goodsItems.length) {
          total += Number(i.laborFee)
        }
        totalPrice += Number(goodsItem.goods.salePrice) * goodsItem.num
      })
    })
    return accAdd(totalPrice, total)
  }
  calcItemTotalPlatformPrice=(arr: Array<any>) =>{
    let total = 0
    let totalPrice = 0
    arr.map(i => {
      if (Number(i.laborFee) !== 0  && i.goodsItems.length) {
        total += Number(i.laborFee)
      }
      i.goodsItems.map(goodsItem => {
        totalPrice += Number(goodsItem.goods.platformPrice) * goodsItem.num
      })
    })
    return accAdd(totalPrice, total)
  }

  calcGoodsItemNum=(arr: Array<any>, eachBuy: number | string): Array<any>=> {
    let newArr: Array<any> = []
    arr.map(i => {
      newArr.push({
        ...i,
        num: Number(eachBuy) * Number(i.baseNum)
      })
    })
    return newArr
  }

  calcProjectTotalPriceAndLaborFee=(tabKey, categoryKey)=> {
    const { List } = this.state
    // let { tabKey, categoryKey } = goods
    let category = List[tabKey].items[categoryKey]
    category.totalLaborFee = this.calcItemTotalLaborFee(category.projectItems)
    category.totalPrice = this.calcItemTotalPrice(category.projectItems)
    category.totalPlatformPrice = this.calcItemTotalPlatformPrice(category.projectItems)

    List[tabKey].items[categoryKey] = category
    this.setState({
      List
    }, () => {
      this.calcTotalPrice()
    })
  }
  // 计算总价
  calcTotalPrice=()=> {
    const { List } = this.state
    let [goodsPrice, originGoodsPrice] = [0, 0, 0]

    for (let i in List) {
      let items = List[i].items
      for (let j in items) {
        if (items[j].isCheck) {
          goodsPrice = accAdd(goodsPrice, items[j].totalPrice)
          originGoodsPrice = accAdd(originGoodsPrice, items[j].totalPlatformPrice)
        }
      }
    }

    this.setState({
      totalPrice: {
        goodsPrice,
        originGoodsPrice
      }
    })
  }

  handleAddCount=(goods)=> {

    let { tabKey, categoryKey, projectKey, goodsKey } = goods
    let { List } = this.state
    goods.num++
    List[tabKey].items[categoryKey].projectItems[projectKey].goodsItems[goodsKey] = goods
    Taro.vibrateShort()
    this._updateDisList(goods, List, 'add')
  }

  handleReduceCount=(goods)=> {
    let { tabKey, categoryKey, projectKey, goodsKey } = goods
    let { List } = this.state
    let isNotChoose = List[tabKey].items[categoryKey].projectItems[projectKey].isNotChoose
    let minBuy = 1
    if (Number(isNotChoose) === 1 &&  goods.num <= minBuy) {
      goods.num = minBuy
      Taro.showToast({
        icon: 'none',
        title: `最小购买为${minBuy}哦`,
        duration: 1000
      })
      return
    } else {
      if (goods.num <= 0) {
        this.calcProjectTotalPriceAndLaborFee(tabKey, categoryKey)
        return
      }
    }
    goods.num--
    List[tabKey].items[categoryKey].projectItems[projectKey].goodsItems[goodsKey] = goods
    Taro.vibrateShort()
    this._updateDisList(goods, List)
  }

  handleDelGoods=(goodsItems, index)=> {
    Taro.showModal({
			title: '温馨提示',
			content: '您确认删除吗？若如需重新选择请退出再进来',
			cancelText: '删除',
			cancelColor: '#FF3B30',
			confirmText: '我再想想',
			confirmColor: '#12b3ff',
		}).then(async res => {
			if (res.cancel) {
				let { List } = this.state
        let { tabKey, categoryKey, projectKey } = goodsItems[index]
        let originProjectItem = List[tabKey].items[categoryKey].projectItems[projectKey]
        let currProjectItem = cloneDeep(originProjectItem)

        currProjectItem.goodsItems = goodsItems.splice(1, index)
        // let currProjectItem = List[tabKey].items[categoryKey].projectItems[projectKey]


        try {
          let data = await this.getLaborFee(currProjectItem)
          currProjectItem.laborFee = data.laborFee
          List[tabKey].items[categoryKey].projectItems[projectKey] = currProjectItem
        } catch (error) {
          List[tabKey].items[categoryKey].projectItems[projectKey] = originProjectItem
        }
        this.setState({
          List
        }, () => {
          this.calcProjectTotalPriceAndLaborFee(tabKey, categoryKey)
        })
			}
		})
  }
  _updateDisList = throttle( async (goods, List, type: string = 'reduce') => {
    let { tabKey, categoryKey, projectKey, goodsKey } = goods
    let currProjectItem = List[tabKey].items[categoryKey].projectItems[projectKey]
    try {
      let data = await this.getLaborFee(currProjectItem)
      currProjectItem.laborFee = data.laborFee
    } catch (error) {
      if (type === 'add') {
        goods.num --
        currProjectItem.goodsItems[goodsKey] = goods
      }
      if (type === 'reduce') {
        goods.num ++
        currProjectItem.goodsItems[goodsKey] = goods
      }
    }
    this.setState({
      List
    }, () => {
      let { tabKey, categoryKey } = goods
      this.calcProjectTotalPriceAndLaborFee(tabKey, categoryKey)
    })

  }, 500)

  // 获取工时费
	getLaborFee=async (currProjectItem)=> {
    let { projectItemId, goodsItems} = currProjectItem
    let formData:any = {}
    formData.projectItemId = projectItemId
    formData.goodsItems = goodsItems.map(i => {
      return {
        goodsId: i.goods.goodsId,
        num: i.num
      }
    })
    if (formData.goodsItems.length === 0) {
      return {
        laborFee: 0
      }
    }
    Taro.showLoading({
      title: '匹配中',
      mask: true
    })
    let res = await getLaborFee(formData)
    setTimeout(() => {
      Taro.hideLoading()
    }, 200)
    return res.data.data
  }

  handleToSelectSpec=(project,category)=> {
    let { baseServiceId, projectItemId, projectId, isNotChoose, categoryKey, projectKey, tabKey } = project
		let mainGoodsId = category.projectItems[0]['goodsItems'][0]['goods']['goodsId']
    Taro.navigateTo({
      url: `/pages/maintain/spec/index?${qs.stringify({
        baseServiceId,
        jekunModelCode: this.props.car.carInfo.currentCar.jekunModelCode,
        projectItemId,
        projectId,
        isNotChoose,
        categoryKey,
        projectKey,
        tabKey,
				mainGoodsId,
      })}`
    })
  }

  handleCheck=(categoryIndex)=> {
    let { List, current } = this.state
    let categoryList = cloneDeep(List[current].items)
    let currentRelatedNum = categoryList[categoryIndex].relatedNum
    let currentCategoryKey = categoryList[categoryIndex].categoryKey
    let category = categoryList[currentCategoryKey]
    let diffCategoryDialog = {
      show: true,
      title: '',
      data: new Array(),
      currentCategoryKey,
      receiveIndex: 0
    }
    let currentRelatedList: Array<any> = []
    for (let i in categoryList) {
      if (currentRelatedNum && String(currentRelatedNum) === String(categoryList[i].relatedNum)) {
        currentRelatedList.push({
          isCheck: categoryList[i].isCheck,
          categoryKey: categoryList[i].categoryKey,
          image: categoryList[i].image,
          projectName: categoryList[i].projectName,
          maintenanceCycle: categoryList[i].maintenanceCycle
        })
      }
    }

    if (currentRelatedList.length > 1) { // 存在多个互斥选项
        let needRelatedCount = 0
        currentRelatedList.map(i => {
          if (i.isCheck) {
            needRelatedCount ++
          }
        })
        if (category.isCheck === false) { // 要选的category
          category.isCheck = !category.isCheck
          currentRelatedList.map(i => {
            if (String(category.categoryKey) === String(i.categoryKey) || i.isCheck) {
              diffCategoryDialog.data.push(i)
            }
          })
          if (needRelatedCount >= 1) {
            this.setState({
              diffCategoryDialog
            })
            return
          }
          List[current].items[currentCategoryKey] = category
          this.setState({
            List
          }, () => { this.calcTotalPrice() })
          return
        }
        category.isCheck = !category.isCheck
        List[current].items[currentCategoryKey] = category
        this.setState({
          List
        }, () => { this.calcTotalPrice() })
    } else {
      category.isCheck = !category.isCheck
      List[current].items[currentCategoryKey] = category
      this.setState({
        List
      }, () => {
        this.calcTotalPrice()
      })
    }
  }
  handleSpecDialogCheck=(item) =>{
    const { List, current, diffCategoryDialog } = this.state

    let currentCheck = List[current].items[item.categoryKey].isCheck
    if (currentCheck) return
    let items = List[current].items
    let dialogItem = diffCategoryDialog.data

    // 为互斥项的重置选中
    for (let i in items) {
      for (let j in dialogItem) {
        if (String(items[i].categoryKey) === String(dialogItem[j].categoryKey)) {
          items[i].isCheck = false
        }
      }
    }
    List[current].items[item.categoryKey].isCheck = true

    diffCategoryDialog.data.map(i => i.isCheck = false)
    item.isCheck = true

    diffCategoryDialog.show = false
    this.setState({
      diffCategoryDialog,
      List
    }, () => {
      this.calcTotalPrice()
    })
  }
  handleCloseDialog=()=> {
    let { diffCategoryDialog } = this.state
    diffCategoryDialog.show = false
    this.setState({
      diffCategoryDialog
    })
  }
  handleCloseCouponDialog=()=> {
    let { couponDialog } = this.state
    couponDialog.show = false
    this.setState({
      couponDialog
    })
  }
  handleGetReceiveCoupon =async (item)=> {
    let { couponDialog } = this.state
    let { sendType, data } = couponDialog

    if (Number(sendType) === 2) { // 多选
      if (item.status === 1) { // 已领取
        return
      } else {
        Taro.showLoading({
          title: '正在领取中',
          mask: true
        })
        await receiveCoupon({
          couponIdCode: item.couponIdCode
        })
        this.handleReceiveCoupon(couponDialog)
        setTimeout(() => {
          Taro.hideLoading()
        }, 200)
      }
    } else {
      if (Number(item.status) === 1) return
      let receiveFlag = false
      data.map(i => { if (Number(i.status) === 1) receiveFlag = true })
      if (receiveFlag) {
        Taro.showToast({
          icon: 'none',
          title: '你已领取过优惠券拉，请购买保养商品进行使用',
          duration: 2000
        })
        return
      }
      Taro.showLoading({
        title: '正在领取中',
        mask: true
      })
      await receiveCoupon({
        couponIdCode: item.couponIdCode
      })
      this.handleReceiveCoupon(couponDialog)
      setTimeout(() => {
        Taro.hideLoading()
      }, 200)
    }
  }
  handleSubmit = debounce(() => {
    if (!this.isCanSubmitFlag) return
    let { List,selectStore } = this.state
		if (!selectStore.storeName) {  // 加入购物车的时候需要先选择下单门店
			Taro.showToast({
				title: '请先选择下单门店！',
				icon: 'none',
				duration: 2000,
			})
			return
    }
    const { car } = this.props
    const goodsData: any = []
    List.forEach(category => {
      category.items.forEach(item => {
        if (item.isCheck) {
          item.projectItems.forEach(project => {
            project.goodsItems.forEach(goods => {
              const { goodsId, defaultGoodsSkuId: goodsSkuId,  } = goods.goods
              if (goods.num > 0) {
                goodsData.push({
                  goodsId,
                  goodsSkuId,
                  number: goods.num,
                  directBuy: 1,
                  itemType: 1
                })
              }
            })
          })
        }
      })
    })
    if (!goodsData.length) return
    Taro.showLoading({
      title: '加入购物车中',
      mask: true
    })
		console.log('goodsData--goodsData',goodsData)
    createCart({
      goodsData: JSON.stringify(goodsData),
			storeCode:selectStore.storeCode
    }).then(res => {
        const data = res.data.data
        Taro.navigateTo({
          url: '/pages/order/index/index?cartIds=' + JSON.stringify(data.cartIds)
        })
        this.isCanSubmitFlag = false
        Taro.hideLoading()
        setTimeout(() => {
          this.isCanSubmitFlag = true
        }, 100)
    }).catch(error => {
      Taro.showToast({
        icon: 'none',
        title: error.data.data.message,
        duration: 2000
      })
      this.isCanSubmitFlag = true
    }).then(_ => {
      // Taro.hideLoading()
    })
  }, 1000)
  handleClickTab=(value)=> {
    let { List, current } = this.state
    if (current === value) return
    this.setState({
      current: value,
      List: [],
      _scrollIntoView: 'id' + value
    }, () => {
      setTimeout(() => {
        this.setState({
          List: cloneDeep(List)
        })
      }, 100)
    })

  }

  handleReceiveCoupon =async(category, immediate: boolean = false)=> {
    const { couponDialog } = this.state
    if (immediate) {
      couponDialog.show = true
      couponDialog.data = []
      this.setState({
        couponDialog
      })
    }
    let res = await getCouponList({
      projectId: category.projectId
    })

    couponDialog.show = true
    couponDialog.data = res.data.data.item
    couponDialog.sendType = res.data.data.sendType
    couponDialog.projectId = category.projectId
    this.setState({
      couponDialog
    })
  }

  handleEdit=(category)=> {

    let { List, current } = this.state
    let newList = cloneDeep(List)
    let isEdit = newList[current].items[category.categoryKey].isEdit
    newList[current].items[category.categoryKey].isEdit = !isEdit
    this.setState({
      List: newList
    })
  }

  handkeSave=(category)=> {
    let { List, current } = this.state
    let newList = cloneDeep(List)
    let isEdit = newList[current].items[category.categoryKey].isEdit
    newList[current].items[category.categoryKey].isEdit = !isEdit
    this.setState({
      List: newList
    })
  }

	// 选择门店
  selectStores() {
		let {selectStore } = this.state
    let { List } = this.state
    const goodsData: any = []
    List.forEach(category => {
      category.items.forEach(item => {
        if (item.isCheck) {
          item.projectItems.forEach(project => {
            project.goodsItems.forEach(goods => {
              const { goodsId, defaultGoodsSkuId: goodsSkuId,  } = goods.goods
              if (goods.num > 0) {
                goodsData.push({
                  goodsId,
                  goodsSkuId,
                  number: goods.num,
                  directBuy: 1,
                  itemType: 1
                })
              }
            })
          })
        }
      })
    })
		let goodsIds = []
    if (goodsData && goodsData.length !== 0) {
      goodsIds = goodsData.map(v => {
        const { goodsId } = v
        return goodsId
      })
    }
		let url =`/pages/store/platform/index?goodsIds=${String(goodsIds)}`
		if(selectStore.storeCode){
			url = `/pages/store/platform/index?goodsIds=${String(goodsIds)}&storeCode=${selectStore.storeCode}`
		}
		Taro.navigateTo({
			url
		})
  }

  catchTouchMove = event => {
    event.stopPropagation()
    event.preventDefault()
  }
  render() {
    const scrollStyle = {
      height: '100vh'
    }
		console.log('this',this)
    const {
      List,
      tabs,
      couponDialog,
      scrollTop,
      diffCategoryDialog,
      totalPrice,
      loading,
      _scrollIntoView,
      giftRuleList,
			selectStore
    } = this.state
    let categoryList: Array<any> = []
    if (List.length > 0) {
      categoryList = List[this.state.current].items
    }

    return (
      <View className='maintain-list-wrap'>
        <View className='dialog-tips'>
          <AtFloatLayout scrollY isOpened={diffCategoryDialog.show} onClose={this.handleCloseDialog.bind(this)} title='温馨提示'>
            <View className='dialog-tips-wrap'>
              <View className='dialog-tips-wrap-head'>
                <Text className='category-name'>{ diffCategoryDialog.data.length > 0 &&  diffCategoryDialog.data[0].projectName }</Text>和
                <Text className='category-name'>{ diffCategoryDialog.data.length > 0 &&  diffCategoryDialog.data[1].projectName }</Text>
                两个项目不需要同时保养，请选择其中一个项目。
              </View>
              <View className='dialog-tips-wrap-content'>
                { diffCategoryDialog && diffCategoryDialog.data.map(item =>
                  <View className={
                    classnames('item', {
                      'is-check': item.isCheck
                    })}
                    key={String(item.categoryKey)}
                    onClick={this.handleSpecDialogCheck.bind(this, item)}
                  >
                    <View
                      className='checked-icon'
                    ></View>
                    <View className='cont'>
                      <View className='cont-left'>
                        <Image className='icon-img' mode='aspectFill' lazyLoad src={item.image}></Image>
                      </View>
                      <View className='cont-right'>
                        <View className='cont-right-top'>{item.projectName}</View>
                        <View className='cont-right-bottom'>{item.maintenanceCycle}</View>
                      </View>
                    </View>
                  </View>
                )}
              </View>
            </View>
          </AtFloatLayout>
        </View>
        <View className='dialog-coupon'>
          <AtFloatLayout scrollY isOpened={couponDialog.show} onClose={this.handleCloseCouponDialog.bind(this)} title='领取优惠券'>
            <View className='dialog-coupon-wrap'>
              <View className='dialog-coupon-wrap-content'>
                { couponDialog.data.map((item, index)=>
                  <View className={
                    classnames('item', {
                      'is-receive': true
                    })}
                    key={String(index)}
                    onTouchStart={this.handleGetReceiveCoupon.bind(this, item)}
                  >
                    <View className='left'>
                      <View className='left-wrap'>
                        <View className='money'>¥{Number(item.baseAmount)}</View>
                        { Number(item.minPrice) !== 0 && <View className='limit-money'>满{Number(item.minPrice)}元使用</View> }
                      </View>
                    </View>
                    <View className='right'>
                      <View className='right-wrap'>
                        <View className='top'>
                          { Number(item.vipLimit) === 1 && <View className='vip'><View className='vip-icon'></View>VIP会员专享</View> }
                          <View className='coupon-name'>{item.couponName}</View>
                        </View>
                        <View className='bottom'>
                          <Text className='tip'>{ item.validDateLabel }</Text>
                          <View className='btn-wrap'>
                            { Number(item.status) === 0 && <AtButton type='primary'>立即领取</AtButton> }
                            { Number(item.status) === 1 && <AtButton type='secondary' onClick={this.handleCloseCouponDialog.bind(this)}>立即使用</AtButton> }
                          </View>
                        </View>
                      </View>
                    </View>
                    { Number(item.status) === 1 && <View className='is-receive'></View> }
                  </View>
                )}
              </View>
            </View>
          </AtFloatLayout>
        </View>
        <View className='car-info'>
          <CarInfo />
        </View>
        { tabs.length > 0 &&
          <View className='nav-scroll'>
            <ScrollView scrollX scroll-with-animation scroll-into-view={_scrollIntoView} scrollY={false} className='nav-scroll-wrap'>
              <View className={
                classnames('narbar-wrap')
              }
              >
                {tabs.map((item, index) =>
                  <View
                    id={'id' + (index + 1)}
                    className={
                      classnames('item', {
                        'active': item.tabKey === this.state.current
                      })
                    }
                    onTouchStart={this.handleClickTab.bind(this, index)}
                    key={'narbar' + index}
                  >
                    <Text className='text'>{item.name}</Text>
                  </View>
                )}
              </View>
            </ScrollView>

          </View>
        }

        {
          giftRuleList.length && <View className='gift-rule-wrap'>
            <View className='gift-rule'>
              <Text>限时优惠：{ giftRuleList.map(i => i.description).join('，')}</Text>
            </View>
          </View>
        }

        <View className='cart-wrap'>
          <View className='cart'>
            <View className='left'>
              {/* <Image className='cart-img' mode='aspectFill' src={this.cartImg}></Image> */}
              <View className='count'>
                <View>¥<Text className='total'>{totalPrice.goodsPrice}</Text><Text className='origin-total'>￥{totalPrice.originGoodsPrice}</Text></View>
                <View className='tip'>
                  <Text>含安装工时费</Text>
                </View>
              </View>
            </View>
            <View className={classnames('btn', {
              'disabled': parseInt(totalPrice.goodsPrice) <= 0 || totalPrice.goodsPrice === '--'
            })} onClick={this.handleSubmit.bind(this)}
            >
              去结算
						</View>
          </View>
        </View>
        <ScrollView className='list-wrap' scrollWithAnimation enableBackToTop scrollTop={scrollTop} scrollY onScroll={this.onScroll.bind(this)} style={scrollStyle}>
          <View className='content-wrap'>
            {categoryList && categoryList.length > 0 ? categoryList.map((category, categoryIndex) =>
              <View className='content-wrap-item' key={Number(category.id)}>
                <View className='content-wrap-item-head'>
                  <View className='left' onTouchStart={this.handleCheck.bind(this, categoryIndex)}>
                    <View
                      className={classnames('checked-icon', {
                        'is_check': category.isCheck
                      })}

                    ></View>
                    <View className='title-info'>
                      <Image className='icon-img' mode='aspectFill' lazyLoad src={category.image}></Image>
                      <View className='info'>
                        <Text className='title'>{category.projectName}</Text>
                        <Text className='desc'>{category.maintenanceCycle}</Text>
                      </View>
                    </View>
                  </View>
                  <View className='right'>
                    {
                      Number(category.isCoupon) === 1 &&
                      <View className='coupon-btn' onTouchStart={this.handleReceiveCoupon.bind(this, category, true)}>
                        <View className='icon'></View>
                        <Text>领券</Text>
                      </View>
                    }
                    <Text className='desc'>￥{Number(category.totalPrice)}</Text>
                  </View>
                </View>
                <View className={
                  classnames('content-wrap-item-eidt-wrap', {
                    'show': category.isCheck,
                    'hide': !category.isCheck
                  })
                }
                >
                  <Text className='title'>项目清单</Text>
                  <View className='eidt'>
                    {
                      !category.isEdit && <View className='edit-btn' onTouchStart={this.handleEdit.bind(this, category)}>
                        <View className='edit-icon'></View>
                        <Text className='text'>编辑</Text>
                      </View>
                    }
                    {
                      category.isEdit && <View className='save-btn' onTouchStart={this.handkeSave.bind(this, category)}>
                        <View className='save-icon'></View>
                        <Text className='text'>保存</Text>
                      </View>
                    }
                  </View>
                </View>
                {category.projectItems.map((project, projectIndex) =>
                  <View className={classnames('content-wrap-item-content', {
                    'show': category.isCheck,
                    'hide': !category.isCheck,
                    'edit-view': category.isEdit
                  })} key={'category' + projectIndex}
                  >
                    {category.isEdit && project.goodsItems.map((goods, goodsIndex) => {
                      // let num = this.state.List[goods.tabKey].items[goods.categoryKey].projectItems[goods.projectKey].goodsItems[goods.goodsKey].num
                      return <View className='item-info' key={'goods' + goodsIndex} >
                        <View className='left'>
                          <Image className='annual-img' mode='aspectFill' src={goods.goods.thumbnailUrl}></Image>
                        </View>
                        <View className='right'>
                          <View className='input-num'>
                            <View className='down number-action' onTouchStart={this.handleReduceCount.bind(this, goods)}>
                              {
                                ((Number(project.isNotChoose) === 1 && Number(goods.num) > 1) || (Number(project.isNotChoose) === 0 && Number(goods.num) > 0)) &&
                                <Iconfont size='24' color='#333' name='icon-jian-gaoliang' /> }
                              {
                                ((Number(project.isNotChoose) === 1 && Number(goods.num) === 1) || (Number(project.isNotChoose) === 0 && Number(goods.num) === 0)) &&
                                <Iconfont size='24' color='#eee' name='icon-jian-gaoliang' />
                              }
                            </View>
                            <View  className='number'>{goods.num}</View>
                            <View className='up number-action' onTouchStart={this.handleAddCount.bind(this, goods)}>
                              <Iconfont size='24' color='#fff' name='icon-jia-gaoliang' />
                            </View>
                          </View>
                          <View className='action-wrap'>
                            {/* { project.isNotChoose === 0 && <Text className='del' onTouchStart={this.handleDelGoods.bind(this, project.goodsItems, goodsIndex)}>删除</Text> } */}
                            <View className='exchange' onTouchStart={this.handleToSelectSpec.bind(this, project,category)}>更换</View>
                          </View>
                        </View>
                      </View>
                    })}
                    {!category.isEdit && project.goodsItems.map((goods, goodsIndex) =>
                      <View className='item-info' key={'goods' + goodsIndex} onClick={()=>this.handleClick(goods.goods)}>
                        <View className='left'>
                          <Image className='annual-img' mode='aspectFill' src={goods.goods.thumbnailUrl}></Image>
                        </View>
                        <View className='right'>
                          <Text className='goods-name'>{goods.goods.goodsName}</Text>
                          <View className='r-bottom-wrap'>
                            <View className='r-bottom-t'>
                              {goods.goods.tags && goods.goods.tags.length && <Text className='tag'>{goods.goods.tags.join(',')}</Text>}
                              {/* <Text>已售出{goods.goods.saleCount}件</Text> */}
                            </View>
                            <View className='r-bottom-b'>
                              <View className='r-bottom-b-r'>
                                ￥<Text className='price'>{Number(goods.goods.salePrice)}</Text>
                                {/* <Text className="origin-price">￥{goods.goods.platformPrice}</Text> */}
                              </View>
                              <Text className='count'>x {goods.num}</Text>
                            </View>
                          </View>
                        </View>
                      </View>
                    )}
                  </View>
                )}
                <View className='content-wrap-item-bottom'>
                  <View className='content-wrap-item-bottom-left'>
                    <View>
                      <View></View>
                      <Text>工时费：</Text>
                    </View>
                    <Text className='wage'>￥{category.totalLaborFee}</Text>
                  </View>
                </View>
              </View>
            ):<View className='loading-page'>
							正在加载数据...
							</View>}
						{
							categoryList && categoryList.length > 0 ? (
								<View className='maintner-goods-view' onClick={() => { this.selectStores() }}>
								<View className='title'  >
									<View className='span'>下单门店</View>
									<View className='em'></View>
								</View>
								<View className='distance'>
									<View className='text'>{ selectStore && selectStore.storeName || '请选择下单门店' }</View>
									<Iconfont size='26' color='#ccc' name='icon-jiantourukou' />
								</View>
							</View>
							) : null
						}

          </View>
        </ScrollView>
        <AtMessage />
      </View>
    )
  }
}
